#!/usr/bin/python3
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# ******************************************************************************/
"""
Description: modify method's entrance for custom commands
Class:ModifyCommand
"""
from javcra.application.checkpart.checktest import CheckTest
from javcra.application.modifypart.modifyentrance import IssueOperation
from javcra.application.serialize.serialize import ModifySchema
from javcra.cli.base import BaseCommand
from javcra.application.serialize.validate import validate_giteeid, validate
# from javcra.application.modifypart.modifyentrance import ModifyEntrance
from javcra.common.constant import PERMISSION_DICT, GITEE_TOKEN


class ModifyCommand(BaseCommand):
    """
    Description: start the modiy part
    Attributes:
        sub_parse: Subcommand parameters
        params: Command line parameters
    """

    def __init__(self):
        """
        Description: Instance initialization
        """
        super(ModifyCommand, self).__init__()
        self.sub_parse = BaseCommand.subparsers.add_parser(
            'modify', help="release assistant of modify part")
        self.add_issueid_arg()
        self.add_giteeid_arg()
        group = self.sub_parse.add_mutually_exclusive_group(required=True)
        group.add_argument(
            '--add',
            help='adding a list of issues which would add to cve, bugfix and remain list',
            default='',
            action='store',
            choices=['cve', 'bugfix', 'remain']
        )
        group.add_argument(
            '--delete',
            help='deleting a list of issues which would add to cve, bugfix and remain list',
            default='',
            action='store',
            choices=['cve', 'bugfix', 'remain']
        )
        self.sub_parse.add_argument(
            '--id',
            help='the list of issueid which would add/del to cve, bugfix and remain list',
            action='store',
            nargs='*',
            required=True,
        )

    def do_command(self, params):
        """
        Description: Executing command
        Args:
            params: Command line parameters
        Returns:

        Raises:

        """
        issue_id = params.releaseIssueID
        gitee_id = params.giteeid

        param_dict = {
            "issueid": params.releaseIssueID,
            "giteeid": params.giteeid,
            "id": params.id,
            "choice": params.add or params.delete
        }
        result, error = validate(ModifySchema, param_dict, load=True)
        if error:
            print(error)
            return

        issue_list = params.id
        modify_type = ''
        print("list", issue_list)
        if params.add:
            modify_type = params.add
            action = 'add'
        elif params.delete:
            modify_type = params.delete
            action = 'delete'
        else:
            print("Cannot parse the parameter")
            return

        if modify_type == "remain":
            comment = "/no-release"
        else:
            comment = "/" + action + "-" + modify_type

        print("modify part start!", issue_id, gitee_id, issue_list)

        # 需增加这两个参数
        _repo = "pkgship"

        # TODO:更多入口请从命令行解决 当前这个只是实现类的地方
        s = IssueOperation(_repo, GITEE_TOKEN, issue_id)
        check = CheckTest(_repo, GITEE_TOKEN, params.releaseIssueID)
        personnel_authority = check.parsing_body()
        permission = validate_giteeid(gitee_id, comment, personnel_authority)
        if not permission:
            return

        modify_res = s.operate_release_issue(operation=action, operate_block=modify_type, issues=issue_list)
        if modify_res:
            print("[INFO] %s %s in %s successfully." % (action, ",".join(issue_list), modify_type))
        else:
            print("[ERROR] failed to %s %s in %s." % (action, ",".join(issue_list), modify_type))

        if modify_type == "remain":
            check_res = s.update_remain_issue_state(issue_list, action)
            if check_res:
                print("update remain issues successfully.")
            else:
                print("failed to update remain issues, please check whether the issue exist in cve and bugfix part.")
